package com.qcit.common.utils

import android.content.Context
import android.content.SharedPreferences
import com.qcit.common.db.User

object QSharedPreferences {
    private const val NAME = "SpinKotlin"
    private const val MODE = Context.MODE_PRIVATE
    private lateinit var preferences: SharedPreferences

    // list of app specific preferences
    private val IS_FIRST_RUN_PREF = Pair("is_first_run", false)
    private val USER = Pair("user", "")
    private val LASTPHONE = Pair("lastphone", "")

    fun init(context: Context) {
        preferences = context.getSharedPreferences(NAME, MODE)
    }

    /**
     * SharedPreferences extension function, so we won't need to call edit() and apply()
     * ourselves on every SharedPreferences operation.
     */
    private inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
        val editor = edit()
        operation(editor)
        editor.apply()
    }

    var firstRun: Boolean
        // custom getter to get a preference of a desired type, with a predefined default value
        get() = preferences.getBoolean(IS_FIRST_RUN_PREF.first, IS_FIRST_RUN_PREF.second)
        // custom setter to save a preference back to preferences file
        set(value) = preferences.edit {
            it.putBoolean(IS_FIRST_RUN_PREF.first, value)
        }

    var user: User?
        get() {
            val user = preferences.getString(USER.first, USER.second)?.toBean<User>();
            if (user == null || user.alias.isEmpty())
                return null
            return user;

        }
        set(value: User?) {
            if (value == null)
                preferences.edit { it.putString(USER.first, "") }
            else
                preferences.edit { it.putString(USER.first, value?.toJson()) }
        }

    var lastPhone: String?
        get() = preferences.getString(LASTPHONE.first, LASTPHONE.second)
        set(value) = preferences.edit { it.putString(LASTPHONE.first, value) }
}